import { useEffect, useState } from "react";
import { request } from "src/request";

export type Category = {
  id?: string;
  name: string;
  image?: string;
}

export function useCategories(): [Category[], () => Promise<void>, boolean] {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response = await request.get('/category');
      setCategories(response.data as Category[]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  return [categories, fetchCategories, loading];
}

export function useCategory(id: string): [Category | undefined, () => Promise<void>, boolean] {
  const [category, setCategory] = useState<Category>();
  const [loading, setLoading] = useState(false);

  const fetchCategory = async () => {
    setLoading(true);
    try {
      const response = await request.get(`/category/${id}`);
      setCategory(response.data as Category);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategory();
  }, []);

  return [category, fetchCategory, loading];
}
